<template>
  <div class="permission-manage" v-if="userStore.user">
    <!-- 顶栏 -->
    <TopBar />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 菜单 -->
      <MenuLine />

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" disabled>权限管理</el-button>
      </div>

      <!-- 权限列表 -->
      <el-table
        :data="users"
        style="width: 100%" border v-loading="loading"
      >

        <el-table-column prop="id" label="用户ID" width="100" align="center" />
        <el-table-column prop="username" label="用户名" min-width="150" />
        <el-table-column prop="role" label="角色" width="150" align="center">
          <template #default="{ row }">
            {{ row.role === 'MANAGER' ? '管理员' : '员工' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">编辑权限</el-button>
          </template>
        </el-table-column>

      </el-table>

      <!-- 添加/编辑弹窗 -->
      <el-dialog
        title="编辑用户权限"
        v-model="dialogVisible"
        width="600px"
        @close="resetForm"
        :close-on-click-modal="false"
      >
        <el-form :model="form" ref="formRef" label-width="120px">
          <el-form-item label="用户名">
            <el-input v-model="formUsername" disabled />
          </el-form-item>
          <el-form-item label="页面权限">
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox
                v-for="(name, path) in permissionOptions"
                :key="path"
                :label="path"
                :disabled="form.role === 'MANAGER'"
              >
                {{ name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="操作权限">
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox label="feedback_reply" :disabled="form.role === 'MANAGER'">
                留言反馈回复
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
  <div v-else class="loading-container">
    <el-empty description="正在加载用户信息..." />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, type FormInstance } from 'element-plus';
import { usePermissionStore, type User, type PermissionForm } from '@/stores/permission';
import { useUserStore } from '@/stores/user';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

const permissionStore = usePermissionStore();
const userStore = useUserStore();

const users = ref<User[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const submitLoading = ref(false);
const form = ref<PermissionForm>({ userId: 0, permissions: [] });
const formUsername = ref('');
const formRef = ref<FormInstance>();

// 权限选项（页面权限）
const permissionOptions = {
  '/announcement-manage': '公告管理',
  '/news-manage': '新闻管理',
  '/department-manage': '部门管理',
  '/vehicle-manage': '车辆管理',
  '/employee-manage': '员工管理',
  '/material-type-manage': '物资类型管理',
  '/material-manage': '物资管理',
  '/material-inbound-manage': '物资入库管理',
  '/material-outbound-manage': '物资出库管理',
  '/feedback-manage': '留言反馈管理',
  '/application-manage': '物资申请管理',
  '/transportation-manage': '运输管理',
};

// 获取用户和权限数据
const fetchData = async () => {
  loading.value = true;
  try {
    const [userData, permData] = await Promise.all([
      userStore.fetchUsers(),
      permissionStore.fetchPermissions(),
    ]);
    console.log('PermissionManage: 用户数据:', userData);
    users.value = userData;
  } catch (error: any) {
    users.value = [];
    ElMessage.error('加载数据失败，请重试');
    ElMessage.error(error.message || '未知错误');
  } finally {
    loading.value = false;
  }
};

// 打开编辑权限弹窗
const openEditDialog = (user: User) => {
  form.value = {
    userId: user.id,
    permissions: permissionStore.permissions[user.id] || [],
  };
  formUsername.value = user.username;
  form.value.role = user.role;
  dialogVisible.value = true;
};

// 提交权限更新
const submitForm = async () => {
  if (!formRef.value) return;
  submitLoading.value = true;
  try {
    await permissionStore.updatePermissions(form.value);
    ElMessage.success('权限更新成功');
    dialogVisible.value = false;
    await fetchData();
  } catch (error: any) {
    console.error('PermissionManage: 提交权限错误:', error);
    ElMessage.error('提交权限失败，请重试');
  } finally {
    submitLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  form.value = { userId: 0, permissions: [] };
  formUsername.value = '';
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 初始化加载
onMounted(async () => {
  await fetchData();
});
</script>

<style scoped>
.permission-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px;
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px;
}

.operation-bar {
  margin-bottom: 20px;
}

.operation-bar h2 {
  font-size: 24px;
  color: #333;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  text-align: right;
}

.el-checkbox {
  margin: 5px 10px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
</style>